import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'

// 响应拦截器
http.intercept.response = async (res) => {
  /** refreshToken 也过期了，跳转登录页面 */
  if (res.config.url === 'https://live-api.itheima.net/refreshToken' && res.data.code !== 10000) {
    const pageStack = getCurrentPages()
    const currentPage = pageStack[pageStack.length - 1]
    const redirectURL = currentPage.route
    wx.redirectTo({ url: `/pages/login/index?redirectURL=/${redirectURL}` })
    return res.data
  }
  /** token 过期, 发请求更新 token */
  if (res.data.code === 401) {
    const app = getApp()
    // console.log(app.refreshToken);
    let refreshRes = await wx.http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: `Bearer ${app.refreshToken}`
      }
    })
    /** 刷新token, 重新发请求 */
    if (refreshRes.code === 10000) {
      app.setToken(refreshRes.data.token, refreshRes.data.refreshToken)
      let newRes = await wx.http({
        ...res.config,
        header: {
          Authorization: `Bearer ${refreshRes.data.token}`
        }
      })
      return newRes
    }
  }
  return res.data
}

/** 请求拦截器 */
http.intercept.request = function (params) {
  const app = getApp()
  let token = app.token
  if (params.header && params.header.Authorization) {
    return params
  } else if (token) {
    if (params.header) {
      params.header.Authorization = `Bearer ${token}`
    } else {
      params.header = { Authorization: `Bearer ${token}` }
    }
  }
  return params
}

wx.http = http

export default http